package cn.stylefeng.guns.modular.info.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.SystemClock;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.stylefeng.guns.base.utils.FootDateUtil;
import cn.stylefeng.guns.constant.Constant;
import cn.stylefeng.guns.modular.info.entity.Game;
import cn.stylefeng.guns.modular.info.entity.LeagueTeam;
import cn.stylefeng.guns.modular.info.mapper.GameMapper;
import cn.stylefeng.guns.modular.info.mapper.SeasonMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @program: guns-vip
 * @description:
 * @author: xiesm
 * @create: 2019-12-30 17:57
 **/
@Service
public class Game2Service extends ServiceImpl<GameMapper, Game> {

    @Autowired(required = false)
    private GameMapper gameMapper;

    public File getGameData2(String date, String endData, ExcelWriter writer, String type) {
        String path = System.getProperty("java.io.tmpdir");
        File tempFile = new File(StrUtil.format("{}{}.xls", path, SystemClock.now()));
        if (endData != null) {
            String year = date.substring(0, 4);

            DateTime time = DateUtil.parse(date);
            DateTime endTime = DateUtil.parse(endData);

            int week1 = DateUtil.weekOfYear(time);
            int week2 = DateUtil.weekOfYear(endTime);
            for (; week1 <= week2; week1++) {
                List<LeagueTeam> leagueTeams = getLeagueTeam(week1, Integer.valueOf(year), type);
                leagueTeams.sort((o1, o2) -> (int) (o1.getDate().getTime() - o2.getDate().getTime()));
                writer.write(leagueTeams, true);
            }
        } else {
            String year = date.substring(0, 4);
            DateTime time = DateUtil.parse(date);
            int week = DateUtil.weekOfYear(time);
            List<LeagueTeam> leagueTeams = getLeagueTeam(week, Integer.valueOf(year), type);
            leagueTeams.sort((o1, o2) -> (int) (o1.getDate().getTime() - o2.getDate().getTime()));
            writer.write(leagueTeams);
        }
        writer.setColumnWidth(1, 20);
        writer.setColumnWidth(2, 20);
        writer.setColumnWidth(5, 20);
        writer.flush(tempFile);
        return tempFile;
    }

    public List<LeagueTeam> getLeagueTeam(int week, Integer year, String type) {
        List<LeagueTeam> leagueTeams = new ArrayList<>();
        //查询本周球赛
        QueryWrapper<Game> gameWrapper = new QueryWrapper<>();
        gameWrapper.between("date", FootDateUtil.getWeekMonday(week - 1, year), FootDateUtil.getWeekSunday(week - 1, year));
        gameWrapper.orderByAsc("date");
        List<Game> games = gameMapper.selectList(gameWrapper);

        //查询本周前1个半月的比赛
        List<Game> agoGames = getGames(week, year);

        //遍历获取上周乌龙球球队本周赛程，包含主队和客队
        games.stream().forEach(game -> {

            Game gameA = getGame(agoGames, game.getFkTeamAId());
            Game gameB = getGame(agoGames, game.getFkTeamBId());
            boolean boo1 = getOwnGame(gameA, game.getFkTeamAId(), type);
            boolean boo2 = getOwnGame(gameB, game.getFkTeamBId(), type);
            if (boo1 || boo2) {
                LeagueTeam leagueTeam = new LeagueTeam();
                leagueTeam.setLeagueName(Constant.leagues.get(Integer.valueOf(game.getFkLeagueId())));
                leagueTeam.setTeamAName(Constant.teamIdDict.get(Integer.valueOf(game.getFkTeamAId())));
                leagueTeam.setTeamBName(Constant.teamIdDict.get(Integer.valueOf(game.getFkTeamBId())));
                leagueTeam.setDate(game.getDate());
                if (boo1) {
                    leagueTeam.setOwnGoalA(String.valueOf(true));
                }
                if (boo2) {
                    leagueTeam.setOwnGoalB(String.valueOf(true));
                }
                if (game.getScore() != null) {
                    leagueTeam.setResultHasOwnGoal(String.valueOf(game.getOwnGoalTeamA() || game.getOwnGoalTeamB()));
                }
                leagueTeams.add(leagueTeam);
            }
        });
        return leagueTeams;
    }

    private List<Game> getGames(int week, Integer year) {
        QueryWrapper<Game> gameWrapperB = new QueryWrapper<>();
        gameWrapperB.isNotNull("score");
        gameWrapperB.between("date", FootDateUtil.getWeekMonday(week - 6, year), FootDateUtil.getWeekSunday(week - 2, year));
        gameWrapperB.orderByDesc("date");
        List<Game> games = gameMapper.selectList(gameWrapperB);
        return games;
    }

    private Game getGame(List<Game> games, Integer teamId) {
        if (CollectionUtil.isEmpty(games)) {
            return null;
        }
        for (int i = 0; i < games.size(); i++) {
            Game game = games.get(i);
            if (Objects.equals(game.getFkTeamAId(), teamId) || Objects.equals(game.getFkTeamBId(), teamId)) {
                return game;
            }
        }
        return null;
    }

    public boolean getOwnGame(Game game, int teamId, String type) {
        boolean boo = false;
        if (game != null) {
            switch (type) {
                case "1":
                    if (game.getFkTeamAId() != null && game.getFkTeamAId() == teamId && game.getOwnGoalTeamA()) {
                        boo = true;
                    }
                    if (game.getFkTeamBId() != null && game.getFkTeamBId() == teamId && game.getOwnGoalTeamB()) {
                        boo = true;
                    }
                    break;
                case "2":
                    if (game.getFkTeamAId() != null && game.getFkTeamAId() == teamId && game.getOwnGoalTeamB()) {
                        boo = true;
                    }
                    if (game.getFkTeamBId() != null && game.getFkTeamBId() == teamId && game.getOwnGoalTeamA()) {
                        boo = true;
                    }
                    break;
            }
        }
        return boo;
    }

    /**
     * 自适应宽度(中文支持)
     *
     * @param sheet
     */
    public static void setSizeColumn(Sheet sheet) {
        short cellNum = sheet.getRow(0).getLastCellNum();
        for (int i = 0; i < cellNum; i++) {
            sheet.autoSizeColumn(i);
            sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 17 / 10);
        }
    }


    public void getSeason(HttpServletResponse response, String date, String endDate, String type) {
        ExcelWriter writer = ExcelUtil.getWriter();
        writer.addHeaderAlias("leagueName", "联赛");
        writer.addHeaderAlias("TeamAName", "主队");
        writer.addHeaderAlias("TeamBName", "客队");
        writer.addHeaderAlias("OwnGoalA", "主队乌龙");
        writer.addHeaderAlias("OwnGoalB", "客队乌龙");
        writer.addHeaderAlias("date", "日期");
        writer.addHeaderAlias("resultHasOwnGoal", "结果");

        getGameData2(date, endDate, writer, type);
        setSizeColumn(writer.getSheet());

        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis() + ".xls");
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            writer.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
        IoUtil.close(out);
    }

}
